package fr.charlott.view.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import fr.charlott.business.dto.ClienteDTO;
import fr.charlott.business.service.ClienteService;

@Component("clienteConverter")
@FacesConverter("clienteConverter")
public class ClienteConverter implements Converter {

	private static ClienteService clienteService;

	public ClienteConverter() {
		super();
	}

	@Autowired(required = true)
	public ClienteConverter(ClienteService clienteService) {
		super();
		ClienteConverter.clienteService = clienteService;
	}

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		long annee = Long.valueOf(value);
		return clienteService.chercherParId(annee);
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		if (value instanceof ClienteDTO) {
			ClienteDTO clienteDTO = (ClienteDTO) value;
			return "" + clienteDTO.getId();
		} else if (value instanceof Long) {
			return "" + value;
		} else {
			throw new IllegalArgumentException("Cannot convert");
		}
	}
}
